﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using TheHeGeoDao;

namespace TheHeGeoManager.Util
{
    class TempTracking
    {
        private Thread _trackingThread;
        private SensorAlertHelper _sensorAlertHelper;
        private bool _shouldStop;

        public TempTracking()
        {
            _sensorAlertHelper = new SensorAlertHelper();
        }

        public void Start()
        {
            _shouldStop = false;
            _trackingThread = new Thread(DoTracking);
            _trackingThread.Start();
        }

        public void Stop()
        {
            _shouldStop = true;
            try
            {
                _trackingThread.Abort();
                _trackingThread = null;
            }
            catch (Exception)
            {
            }
        }

        protected void DoTracking()
        {
            while (!_shouldStop)
            {
                Thread.Sleep(1000);
                foreach (var p in _sensorAlertHelper.DictSensor.Values)
                {
                    if (_shouldStop) return;
                    if (p.Alert())
                    {
                        PrepareSendSms(p);
                    }
                }
            }
            
        }

        protected void PrepareSendSms(SensorAlert sensorAlert)
        {
            var listPq = _sensorAlertHelper.ListtPhanQuyen.Where(p => p.MaDuAn.Equals(sensorAlert.MaDuAn)).ToList();
            var temp = _sensorAlertHelper.DictNsd.Values;
            var listNsd = listPq.Select(n => temp.FirstOrDefault(p => p.UserName.Equals(n.UserName))).ToList();
            string content = "Hệ thống thông báo: Sensor:" + sensorAlert.TenSensor + " thuộc thiết bị:" +
                             sensorAlert.TenThietBi +" - Dự án:" + sensorAlert.TenDuAn + 
                             ". Hiện tại có giá trị trung bình:" + sensorAlert.LastValue + "" +
                             " đã vượt ngưỡng cho phép.";
            SendSms(listNsd,content);
        }

        protected void SendSms(List<NguoiSuDung> nsd, string content)
        {
            
        }
    }
}
